import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

import * as echarts from 'echarts';

import ReactResizeDetector from 'react-resize-detector';
import s from './style.module.css';

const PALETTE = [
	'#E6373A',
	'#F49909',
	'#F5CF00',
	'#7F48FC',
	'#CB38FB',
	'#F52F9A',
];

export default class Echarts extends React.PureComponent {
	static propTypes = {
		className: PropTypes.string,
		option: PropTypes.object,
		getInstance: PropTypes.func,
	};

	static defaultProps = {
		className: '',
		option: {},
		getInstance() {},
	};

	state = {};

	chartRef = React.createRef();

	componentDidMount() {
		this.chart = echarts.init(this.chartRef.current);
		this.props.getInstance(this.chart);
		this.palette = PALETTE;
		this.chart.setOption({
			color: this.palette,
			...this.props.option,
		});
		const this_=this
		this.chart.on('legendselectchanged', function (params) {
			// 覆盖图例原始点击事件
			this_.chart.setOption({
					legend:{selected:{[params.name]: true}}
			})
	});
	}

	componentDidUpdate(prevProps) {
		this.chart.resize();

		if (this.props.option !== prevProps.option) {
			this.chart.setOption({
				color: this.palette,
				...this.props.option,
			});
		}
	}

	componentWillUnmount() {
		echarts.dispose(this.chartRef.current);
		this.props.getInstance(null);
	}

	resize = () => this.chart.resize();

	render() {
		const { className } = this.props;

		return (
			<div className={cn(className, s.echarts)} ref={this.chartRef}>
				<ReactResizeDetector
					handleWidth
					handleHeight
					onResize={this.resize}
				/>
			</div>
		);
	}
}
